<?php
/**
 * 微校主页主控类
 * Author: 孙武 QQ:1228746736
 * Date: 2017/10/28
 * Time: 20:17
 */


namespace Home\Controller;

use Home\Model\IndexModel;
use Think\Controller;

class IndexController extends HomeController
{

    private $_M;//模型

    public function __construct()
    {
        parent::__construct();
        $this->_M = new IndexModel('addr');
    }

    /**
     * 主页页面
     */
    public function index()
    {
//        dump(C());exit;
        $this->assign("title", "微笑云");
        $this->display();
    }


    /**
     * 车票查询界面v1.0.0基本完善
     */
    public function ticketQueryResult()
    {


        $from = $_POST['from'];
        $to = $_POST['to'];
        $time = $_POST['time'];
        //dump($time);//2017-7-16


        //条件验证
        if (!$this->checkAddrQueryInfo()) {
            $this->err('系统数据处理错误！查询车票信息缺失');
            exit;
        }

        //车票信息
        $addrs = $this->_M->getAddrsInfoByFromAndTo($from, $to);

        //处理好的发车信息
        $doneTicketInfo = array();
        foreach ($addrs as $v) {
            $dbTime = date('Y-m-d', $v['addr_depart_time']);
            // var_dump($date);//2017-10-31

            /*过滤数据 */
            if ($dbTime = $time) {
                $v['addr_depart_time'] = $this->getFormateDateFromTimestamp($v['addr_depart_time']);

                //处理必发已发车
                if ($v['addr_depart_condition'] == '1') {

                    $ticketId = $v['addr_id'];
                    $needNum = ($v['addr_depart_person_num']) - ($this->getNeedNum($ticketId));
                    if ($needNum < 0) {
                        $v['title'] = "必发车(售空)";
                    }else{
                        $v['title'] = "必发车(余票$this->getNeedNum($ticketId))";
                    }
                } else {
                    //还需再约的人数
                    $ticketId = $v['addr_id'];
                    $needNum = ($v['addr_depart_person_num']) - ($this->getNeedNum($ticketId));

                    //满人处理
                    if ($needNum > 0) {
                        $v['title'] = "再约" . $needNum . "人可发车";
                    } else {
                        $v['title'] = "售空";
                    }
                }
                $doneTicketInfo[] = $v;
            }

        }

        $this->assign("title", "车票查询结果");
        $this->assign("from", $from);
        $this->assign("to", $to);
        $this->assign("time", $time);
        $this->assign("tickets", $doneTicketInfo);
        $this->display();
    }


    /**
     * 检查车票查询信息是否完整
     * @return bool 完整:true  不完整:false
     */
    private function checkAddrQueryInfo()
    {
        $from = $_POST['from'];
        $to = $_POST['to'];
        $time = $_POST['time'];
        if (empty($from) || empty($to) || empty($time)) {
            return false;
        }
        return true;
    }

    /**
     * 获取车票的所需数目(商家填)
     * 比如说需要32人才能发车
     * @param $ticketId
     * @return mixed
     */
    private function getNeedNum($ticketId)
    {
        $sql = "select od_ticket_num as unit_price from bus_pre_order WHERE od_addr_id = $ticketId";
        $res = D()->query($sql);
        $total = 0;
        foreach ($res as $k => $v) {
            $total += $v['unit_price'];
        }
        return $total;
    }

    /**
     * 订票页面
     */
    public function bookTicket()
    {
        $this->assign("insur", 3);

        if (!empty($_POST)) {

            $selectedPsrPostData = $_POST['checkbox'];

            //选中的用户的id
            $psrIds = array();
            foreach ($selectedPsrPostData as $k => $v) {
                $psrIds[] = $k;
            }
            //数组转换为字符串
            $psrIds = implode(',', $psrIds);

            //根据选中用户的id，获取用户的显示信息
            $sql = "select * from bus_passenger where psr_id in ($psrIds)";
            $psrIds = D()->query($sql);
            $this->assign("psrInfo", $psrIds);

        }

//        处理车票信息
        $ticket = $_GET['ticketId'];
        if ($ticket) {
            //session持久化票据
            session('ticketId', $ticket);
            $ticketInfo = D('addr')->find($ticket);

//           处理时间戳
            $ticketInfo['addr_depart_time'] = date("Y-m-d H:i", $ticketInfo['addr_depart_time']) . " " . $this->changeNumberToweekday(date('w', $ticketInfo['addr_depart_time']));
            $this->assign("ti", $ticketInfo);
        }
        $this->assign("tickedId", $ticket);
        $this->display();
    }


    /**
     * 预定票页面
     */
    public function preBookTicket()
    {
        $this->assign("insur", 3);

        if (!empty($_POST)) {

            $selectedPsrPostData = $_POST['checkbox'];

            //选中的用户的id
            $psrIds = array();
            foreach ($selectedPsrPostData as $k => $v) {
                $psrIds[] = $k;
            }
            //数组转换为字符串
            $psrIds = implode(',', $psrIds);

            //根据选中用户的id，获取用户的显示信息
            $sql = "select * from bus_passenger where psr_id in ($psrIds)";
            $psrIds = D()->query($sql);
            $this->assign("psrInfo", $psrIds);

        }

//        处理车票信息
        $ticket = $_GET['ticketId'];
        if ($ticket) {
            //session持久化票据
            session('ticketId', $ticket);
            $ticketInfo = D('addr')->find($ticket);

//           处理时间戳
            $ticketInfo['addr_depart_time'] = date("Y-m-d H:i", $ticketInfo['addr_depart_time']) . " " . $this->changeNumberToweekday(date('w', $ticketInfo['addr_depart_time']));
            $this->assign("ti", $ticketInfo);
        }
        $this->assign("tickedId", $ticket);
        $this->display();
    }


    /**
     * 根据时间戳返回星期几
     * @param string $time 时间戳
     * @return 星期几
     */
    private function changeNumberToweekday($time)
    {
        $weekday = array('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六');
        return $weekday[$time];

    }


    /**
     * 选择乘客页面
     */
    public function selectPassenger()
    {
        $_ticketId = $_GET['ticketId'];
        if (!empty($_POST)) {

            //检查数据的合法性
            if (($errMsg = $this->checkPassengerInfo($_POST)) !== true) {
                $this->err($errMsg);
                exit;
            }
            $dbData = array(
                'user_id' => session('user_id'),
                'psr_id_card' => $_POST['passengerIdCard'],
                'psr_tel' => $_POST['passengerTel'],
                'psr_name' => $_POST['passengerName'],
                'psr_status' => '1'

            );
            $res = D('passenger')->add($dbData);
        }
        //            根据用户id获取该用户的乘客信息
        //todo  替换用户id
        $userId = 2;//模拟用户id
        session('user_id', $userId);
//            获取乘客信息
        $_map = array("user_id" => $userId);
        $psrIds = D("passenger")->where($_map)->select();

        $this->assign("ticketId", $_ticketId);
//            获取乘客
        $this->assign("psrInfo", $psrIds);
        $this->display();
    }

    /**
     * 检查乘客信息是否合法
     * @param array $array 需要检验的数组
     */
    private function checkPassengerInfo($data = array())
    {

        if (strlen($data['passengerName']) < 2) {
            return "姓名错误";
        }

        if (strlen($data['passengerTel']) != 11) {
            return "电话信息错误";
        }

        if (strlen($data['passengerIdCard']) < 18) {
            return "身份证信息错误";
        }
        return true;
    }

    /**
     * 选择乘客页面
     */
    public function preSelectPassenger()
    {
        $_ticketId = $_GET['ticketId'];
        if (!empty($_POST)) {
            $dbData = array(
                'user_id' => session('user_id'),
                'psr_id_card' => $_POST['passengerIdCard'],
                'psr_tel' => $_POST['passengerTel'],
                'psr_name' => $_POST['passengerName'],
                'psr_status' => '1'

            );
            $res = D('passenger')->add($dbData);
        }
        //            根据用户id获取该用户的乘客信息
        //todo  替换用户id
        $userId = 2;//模拟用户id
        session('user_id', $userId);
//            获取乘客信息
        $_map = array("user_id" => $userId);
        $psrIds = D("passenger")->where($_map)->select();

        $this->assign("ticketId", $_ticketId);
//            获取乘客
        $this->assign("psrInfo", $psrIds);
        $this->display();
    }


    /**
     * 支付界面
     */
    public function payTicket()
    {


//        dump($_POST);
        //车票id
        $_ticketId = session('ticketId');


        //乘客数组
        $psrIds = $_POST['psr'];

        //乘客数量
        $_psrNum = count($psrIds);

        $_ticketInfo = $this->getAddrInfoById(session('ticketId'));

        //单票价
        $unitPrice = $_ticketInfo['addr_price'];


        //根据折扣code获取折扣id
        $dicCode = $_POST['dicCode'];
        $map = array('dc_code' => $dicCode);
        $discountInfo = D('discount')->where($map)->find();


        //保存到数据库信息
        $dbData = array(

            'user_id' => session('user_id'),
            'od_name' => $this->getOrderId(),
            'od_creat_time' => time(),
            'od_finish_time' => '0',
            'od_ticket_num' => $_psrNum,
            "od_total_price" => $this->getTotalPrice(),
            'od_sell_price' => $this->getSellPrice($discountInfo),
            'od_status' => '0',
            'od_psr_ids' => $this->getPsrIds($psrIds),
            'od_addr_id' => $_ticketId,
            'od_insur_price' => $this->getInsurPrice($_psrNum),
            'od_discount_id' => $discountInfo['dc_id'],
            'od_get_ticket_person' => $_POST['get_ticket_pseson'],
            'od_get_ticket_person_tel' => $_POST['get_ticket_tel'],
            'od_pay_status' => '0'

        );


        //检查条件
        if (($errMsg = $this->checkIsPay($dbData)) !== true) {
            $this->err('非法操作', $errMsg);
            exit;
        }

        //保存数据库
        if (!$orderId = D('order')->add($dbData)) {
            die('未知错误,请重试!');
        }


        //给模板传值
        //单价
        $this->assign("unitPrice", $unitPrice);
        //总价
        $this->assign("totalPrice", $this->getTotalPrice());
        //折后价
        $this->assign("sellPrice", $this->getSellPrice($discountInfo));
        //出发地,目的地,时间
        $addrInfo = $this->getAddrInfoById($_ticketId);
        $this->assign("from", $addrInfo['addr_from']);
        $this->assign("to", $addrInfo['addr_to']);
        $this->assign("depart_time", $this->getFormateDateFromTimestamp($addrInfo['addr_depart_time']));
        //乘车人
        $psrInfo = $this->getPsrInfoByPsrIds($psrIds);
        $this->assign("psrInfo", $psrInfo);
        //取票人 取票人电话
        $this->assign("getTicketPersonName", $_POST['get_ticket_pseson']);
        $this->assign("getTicketPersonTel", $_POST['get_ticket_tel']);
        //保险费
        $this->assign("insurPrice", $this->getInsurPrice($_psrNum));


        $this->assign("orderId", $orderId);
        $this->display();


    }



    /**
     * 检查是否能提交购票信息
     * @param $data
     * @return string 错误信息
     */
    private function checkIsPay($data)
    {
        if ($data['user_id'] < 0) return "获取用户认证信息错误";
        if (empty($data['od_name'])) return "生产订单号错误";
        if ($data['od_ticket_num'] <= 0) return "未选择乘车人";
        if ($data['od_total_price'] <= 0) return "计算总价信息出错";
        if ($data['od_sell_price'] <= 0) return "计算销售信息错误";
        if (empty($data['od_psr_ids'])) return "未选择乘车人";
        if (empty($data['od_get_ticket_person'])) return "未填写取票人姓名";
        if (empty($data['od_get_ticket_person_tel'])) return "未填写取票人电话";
        return true;

    }

    /**
     * 根据乘客ids获取乘客信息
     * @param $psrIds
     * @return mixed
     */
    private function getPsrInfoByPsrIds($psrIds)
    {
        $psrIds = rtrim(implode(',', $psrIds), ',');
        $sql = "select * from bus_passenger WHERE psr_id in ($psrIds)";
        return D()->query($sql);
    }


    /**
     * 总价
     * @return mixed
     */
    private function getTotalPrice()
    {
        //车票id
        $_ticketId = session('ticketId');


        //乘客数组
        $psrIds = $_POST['psr'];

        //计算乘客数量
        $_psrNum = count($psrIds);

        //计算价格
        $_ticketInfo = D('addr')->find($_ticketId);

        //单票价
        $unitPrice = $_ticketInfo['addr_price'];

        //总票价
        $_allPrice = $unitPrice * $_psrNum + $this->getInsurPrice($_psrNum);

        return $_allPrice;
    }

    /**
     * 获取乘车人的ids
     * @return string 1,2,3
     */
    private function getPsrIds($data)
    {
        return rtrim(implode(',', $data), ',');

    }


    /**
     * 获取保险价格
     * @return bool
     */
    private function getInsurPrice($psrNum)
    {

        if ($_POST['insur'] > 0) {
            //根据保险加上价格
            $ticketId = session('ticketId');
            $ticketInfo = D('addr')->find($ticketId);
            $insurPrice = $ticketInfo['addr_insur'];
            return $insurPrice * $psrNum;
        }
        return 0;
    }


    /**
     * 获取售价
     * @return bool
     */
    private function getSellPrice($dicInfo)
    {

//        dump($dicInfo['dc_type']);
        //根据折扣打折
        if ($dicInfo['dc_type'] == '1') {
            $sellPrice = $this->getTotalPrice() - $dicInfo['dc_money'];
        } else if ($dicInfo['dc_type'] == '2') {
            $sellPrice = $this->getTotalPrice() * $dicInfo['dc_percent'] * 0.1;
        } else {
            //没有优惠券
            $sellPrice = $this->getTotalPrice();
        }

        //保险价格处理
        return $sellPrice;
    }

    /**
     * 生成订单号
     * @return string
     */
    private function getOrderId()
    {
        $str = "muc";
        $str .= time();
        $str .= rand(1000, 9999);
        return $str;
    }

    /**
     * 根据地址id获取地址信息
     */
    private function getAddrInfoById($addrId)
    {
        return D('addr')->find($addrId);
    }


    /**
     * 根据时间戳得到年月日 时间 星期 2017-07-16 00:00 星期日
     * @param $timestamp
     */
    private function getFormateDateFromTimestamp($timestamp)
    {
        return date("Y-m-d H:i", $timestamp) . " " . $this->changeNumberToweekday(date('w', $timestamp));
    }
}